package com.cn.dim.controller;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.json.Json;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;







import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cn.dim.utils.OssUtil;
import com.cn.dim.utils.StringUtil;
import com.github.pagehelper.Page;



@RestController
@RequestMapping("/test")
public class TestController {

	@RequestMapping("/uploadtest")
	public String toIndex(HttpServletRequest request,HttpServletResponse response){
		//OssUtil.download("file/test2.txt",response);


		DiskFileItemFactory factory = new DiskFileItemFactory();  
		ServletFileUpload upload = new ServletFileUpload(factory);
		
		List<Map<String,Object>> files = new ArrayList<>();
		try {   
			List<FileItem> list = upload.parseRequest(request);  
			for(FileItem item : list){  
				String name = item.getFieldName();  
				
				if(item.isFormField()){  
					String value = item.getString() ;  
					
					//                     request.setAttribute(name, value);  
				}else{  
					/* 以下三步，主要获取 上传文件的名字 
					 */  
					//获取路径名  
					String value = item.getName() ;  
					//索引到最后一个反斜杠  
					int start = value.lastIndexOf("\\");  
					//截取 上传文件的 字符串名字，加1是 去掉反斜杠，  
					String filename = value.substring(start+1);
					
					String realPath=request.getSession().getServletContext().getRealPath("/");  
					String uuid=StringUtil.makeUUID();
					File midFile = new File(realPath+uuid+"/"+filename);
					File fileParent = midFile.getParentFile();
					if (!fileParent.exists()) {
						fileParent.mkdirs();
					}
					try {
						InputStream ins=item.getInputStream();
						OutputStream os = new FileOutputStream(midFile);
						int bytesRead = 0;
						byte[] buffer = new byte[8192];
						while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
						os.write(buffer, 0, bytesRead);
						}
						os.close();
						ins.close();
					} catch (FileNotFoundException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					} catch (IOException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}
					
					
					
					value=uuid+"/"+value;
					String p = OssUtil.uploadfile("file/"+value, midFile);
					System.out.println(p);
					Map<String,Object> map = new HashMap<String,Object>();
					map.put("url", "http://giantlawyer.oss-cn-beijing.aliyuncs.com/"+"file/"+value);
					map.put("filename", filename);
					
					String folderPath=realPath+uuid;
					delFolder(folderPath);
					files.add(map);
				}  
			}  
			PrintWriter out;
			try {
				response.setCharacterEncoding("utf-8");
				out = response.getWriter();
				out.write(JSONArray.fromObject(files).toString());//注意这里向jsp输出的流，在script中的截获方法
				out.flush();
				out.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} catch (FileUploadException e) {  
			e.printStackTrace();  
		}  
		
	
		return null;
	}

	public static boolean delAllFile(String path) {
	       boolean flag = false;
	       File file = new File(path);
	       if (!file.exists()) {
	         return flag;
	       }
	       if (!file.isDirectory()) {
	         return flag;
	       }
	       String[] tempList = file.list();
	       File temp = null;
	       for (int i = 0; i < tempList.length; i++) {
	          if (path.endsWith(File.separator)) {
	             temp = new File(path + tempList[i]);
	          } else {
	              temp = new File(path + File.separator + tempList[i]);
	          }
	          if (temp.isFile()) {
	             temp.delete();
	          }
	          if (temp.isDirectory()) {
	             delAllFile(path + "/" + tempList[i]);//先删除文件夹里面的文件
	             delFolder(path + "/" + tempList[i]);//再删除空文件夹
	             flag = true;
	          }
	       }
	       return flag;
	     }







public static void delFolder(String folderPath) {
    try {
       delAllFile(folderPath); //删除完里面所有内容
       String filePath = folderPath;
       filePath = filePath.toString();
       java.io.File myFilePath = new java.io.File(filePath);
       myFilePath.delete(); //删除空文件夹
    } catch (Exception e) {
      e.printStackTrace(); 
    }
}
	

}
